﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic._Item;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.CoreBusinessLogic.PurchaseOrder;
using SCMS.CoreBusinessLogic.Security;
using SCMS.UI.Models;
using SCMS.Model;
using System.Data.Objects.DataClasses;
using SCMS.Resource;

namespace SCMS.UI.Controllers
{
    public class QuickSearchController : PortalBaseController
    {

        private IItemService itemService;
        private IOrderRequest orderSvc;
        private IPurchaseOrderService purSvc;
        private IOrderRequest orderRequestService;

        public QuickSearchController(IPermissionService permissionService, IUserContext userContext, IItemService _itemService, IOrderRequest _orderSvc, IPurchaseOrderService _purSvc, IOrderRequest orderRequestService)
            : base(userContext, permissionService)
        {
            this.itemService = _itemService;
            this.orderSvc = _orderSvc;
            this.purSvc = _purSvc;
            this.orderRequestService = orderRequestService;
        }

        public ActionResult Index(FormCollection form)
        {
            List<SimpleViewData> results = new List<SimpleViewData>();

            string cat = form["category_search"];
            string phrase = form["search_text"];

            switch (cat)
            {

                case "PO Number":

                    List<Model.PurchaseOrder> pos = purSvc.Search(phrase);
                    foreach (Model.PurchaseOrder p in pos)
                    {
                        results.Add(new SimpleViewData(p.Id.ToString(), p.RefNumber, "/QuickSearch/ViewPurchaseOrdersDetails"));
                    }

                    break;

                case "OR Number":
                    List<Model.OrderRequest> orders = orderSvc.Search(phrase);
                    foreach (Model.OrderRequest i in orders)
                    {
                        results.Add(new SimpleViewData(i.Id.ToString(), i.RefNumber, "/QuickSearch/ViewOrderRequestItems"));
                    }

                    break;
                case "Item Number":
                    List<ItemView> _items = this.itemService.SearchBySerial(countryProg.Id, phrase);

                    foreach (ItemView i in _items)
                    {
                        results.Add(new SimpleViewData(i.item.Id.ToString(), i.item.Name, "/QuickSearch/ItemView"));
                    }

                    break;
                case "Item Name":
                default:
                    List<ItemView> items = this.itemService.GetItems1(countryProg.Id, phrase);

                    foreach (ItemView i in items)
                    {
                        results.Add(new SimpleViewData(i.item.Id.ToString(), i.item.Name, "/QuickSearch/ItemView"));
                    }

                    break;
            }

            ViewBag.SearchTitle = string.Format(Resources.QuickSearchController_String_SearchForPhraseByCategory, phrase, cat);
            ViewBag.Results = results;

            return View();
        }


        public ActionResult ViewPurchaseOrdersDetails(Guid id)
        {

            ViewPOrderItems POItmz;
            List<ViewPOrderItems> POItemList = new List<ViewPOrderItems>();
            using (var context = new SCMSEntities())
            {
                Model.PurchaseOrder Po = context.PurchaseOrders.SingleOrDefault(p => p.Id == id);
                EntityCollection<PurchaseOrderItem> POItemz = Po.PurchaseOrderItems;
                foreach (PurchaseOrderItem item in POItemz)
                {
                    POItmz = new ViewPOrderItems();
                    POItmz.EntityPOItem = item;
                    POItmz.BudgetLine = context.ProjectBudgets.SingleOrDefault(p => p.Id == item.BudgetLineId).LineNumber;
                    POItmz.ProjectNo = item.PurchaseOrder.OrderRequest.ProjectDonor.ProjectNumber;
                    POItmz.Unitmessue = item.OrderRequestItem.Item.UnitOfMeasure.Code;
                    OrderRequestItem orit = item.OrderRequestItem;
                    Item itm = orit.Item;
                    POItemList.Add(POItmz);
                }

                ViewPOs model = new ViewPOs();

                model.POEntiy = Po;
                model.supplier = context.Suppliers.SingleOrDefault(p => p.Id == Po.SupplierId).Name;
                model.paymentTerm = context.PaymentTerms.SingleOrDefault(p => p.Id == Po.PaymentTermId).Code;
                model.shippingTerm = context.ShippingTerms.SingleOrDefault(p => p.Id == Po.ShippingTermId).Name;
                model.POItems = POItemList;
                model.deleliveryDate = (DateTime)Po.LatestDeliveryDate;
                model.PODate = (DateTime)Po.PreparedOn;
                model.StaffEntity = context.Staffs.SingleOrDefault(p => p.Id == Po.PreparedBy);
                model.TotalAmount = Po.TotalAmount;
                model.MBValue = Po.MBValue;
                Person ps = model.StaffEntity.Person;
                Designation ds = model.StaffEntity.Designation;
                if ((bool)Po.IsReviewed)
                {
                    model.ReviewdBy = context.Staffs.SingleOrDefault(p => p.Id == Po.ReviewedBy);
                    var person = model.ReviewdBy.Person;
                    var desg = model.ReviewdBy.Designation;
                    model.ReveiwDate = Po.ReviewedOn.Value;
                }
                if ((bool)Po.IsAuthorized)
                {
                    model.AuthorizdBy = context.Staffs.SingleOrDefault(p => p.Id == Po.AuthorizedBy);
                    var person = model.AuthorizdBy.Person;
                    var desg = model.AuthorizdBy.Designation;
                    model.AuthorizDate = Po.AuthorizedOn.Value;
                }

                TenderAnalysi ta = Po.TenderAnalysi;
                Model.OrderRequest or = Po.OrderRequest;
                Location loc = Po.Location;
                ViewBag.Currency = or.Currency.ShortName;
                ViewBag.MBCurrency = mbCurrency.ShortName;
                return View("../PurchaseOrder/ViewPurchaseOrdersDetails", "_GeneralLayout", model);
            }
        }


        public ActionResult ViewOrderRequestItems(Guid id)
        {

            decimal total = 0;
            UI.Models.ViewOR OR;
            UI.Models.ViewORDetails ORD;
            List<Models.ViewORDetails> mm = new List<ViewORDetails>();
            using (var db = new SCMSEntities())
            {
                Model.OrderRequest ORRqst = db.OrderRequests.SingleOrDefault(p => p.Id == id);
                Currency mbCurr = db.Currencies.SingleOrDefault(c => c.Id == ORRqst.MBCurrencyId);
                var pd = ORRqst.ProjectDonor;
                if (mbCurr != null)
                    ViewBag.MBCurrency = mbCurr.ShortName;
                OR = new ViewOR();
                OR.EntityOR = ORRqst;
                OR.PreparedBy = db.Staffs.SingleOrDefault(p => p.Id == ORRqst.PreparedBy);
                Person ps = OR.PreparedBy.Person; Designation d = OR.PreparedBy.Designation;
                OR.IssueDate = ORRqst.PreparedOn.Value;
                if ((bool)ORRqst.IsReviewed)
                {
                    OR.ReviewdBy = db.Staffs.SingleOrDefault(p => p.Id == ORRqst.ReviewedBy);
                    var desg = OR.ReviewdBy.Designation;
                    var person = OR.ReviewdBy.Person;
                    OR.ReveiwDate = ORRqst.ReviewedOn.Value;
                }
                if ((bool)ORRqst.IsAuthorized)
                {
                    OR.AuthorizdBy = db.Staffs.SingleOrDefault(p => p.Id == ORRqst.AuthorizedBy);
                    var desg = OR.AuthorizdBy.Designation;
                    var person = OR.AuthorizdBy.Person;
                    OR.AuthorizDate = ORRqst.AuthorizedOn.Value;
                }

                OR.RequestDate = ORRqst.OrderDate.Value;
                OR.curency = db.Currencies.SingleOrDefault(p => p.Id == ORRqst.CurrencyId).ShortName;
                OR.Donor = db.ProjectDonors.SingleOrDefault(p => p.Id == ORRqst.ProjectDonorId).Donor.ShortName;
                OR.RDD = db.Locations.SingleOrDefault(p => p.Id == ORRqst.RequestedDestinationId).Name;
                OR.FDD = db.Locations.SingleOrDefault(p => p.Id == ORRqst.FinalDestinationId).Name;
                OR.project = db.Projects.FirstOrDefault(p => p.Id == ORRqst.ProjectId).Name;
                List<Model.OrderRequestItem> ORItemsList = orderRequestService.GetOrderRequestItems(id);

                foreach (Model.OrderRequestItem item in ORItemsList)
                {
                    total += item.EstimatedPrice;
                    ORD = new ViewORDetails();
                    ORD.EntityORDetails = item;
                    Item it = item.Item;
                    ORD.ProjectNo = orderRequestService.GetProjectDonorDetails((Guid)item.OrderRequest.ProjectDonorId).ProjectNumber;
                    ORD.BudgetLine = orderRequestService.GetProjectBudgetDetails((Guid)item.BudgetLineId).LineNumber;
                    mm.Add(ORD);
                }
                OR.TotalCost = total;
                OR.MBValue = ORRqst.MBValue;
                OR.ORDetails = mm;
                return View("../OrderRequest/ViewOrderRequestItems", "_GeneralLayout", OR);
            }

        }


        public ActionResult ItemView(Guid id)
        {
            List<ItemView> items = new List<ItemView>();

            ItemView iv = itemService.GetItemView(id);
            
            if (iv != null) {
                items.Add(iv);
            }

            return View("../Item/ListView", "_GeneralLayout", items);
        }


    }

    public class SimpleViewData
    {
        public SimpleViewData(string id, string description, string link)
        {
            this.Id = id;
            this.Description = description;
            this.Link = link;
        }
        public string Id;
        public string Description;
        public string Link;
    }
}
